import java.io.*;
import java.net.*;

public class ClientHandler implements Runnable {
    private Socket socket;
    private BufferedReader input;
    private PrintWriter output;
    private boolean peerMatch;
    private int room;
    private static Socket[] clients = new Socket[100];
    private static boolean[] roomMatch = new boolean[100];

    public ClientHandler(Socket socket) throws IOException {
        this.socket = socket;
        peerMatch = false;
        input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        output = new PrintWriter(socket.getOutputStream(), true);
    }

    @Override
    public void run() {
        try {
            do {
                // 处理来自客户端的房间申请信息
                String message = input.readLine();
                room = Integer.parseInt(message) / 100000;
                System.out.println(socket.getInetAddress().getHostName() + ":" + socket.getPort());
                if (roomMatch[room]) {
                    output.println("0000000");
                    socket.close();
                    break;
                } else if (Integer.parseInt(message) % 100000 == 99999) {
                    Socket peerSocket = null;
                    synchronized (clients) {
                        while (peerSocket == null) {
                            if (clients[room] == null) {
                                clients[room] = socket;
                                roomMatch[room] = false;
                                output.println("" + (Integer.parseInt(message) - 9));
                                clients.wait();
                            } else if (clients[room] != null && !roomMatch[room]) {
                                Socket peer = clients[room];
                                if (peer != socket) {
                                    peerSocket = peer;
                                    roomMatch[room] = true;
                                    output.println("" + (Integer.parseInt(message) - 8));
                                }
                            }
                        }
                    }
                    System.out.println(
                            "MATCHED:" + peerSocket.getInetAddress().getHostName() + ":" + peerSocket.getPort());
                    output.println("MATCHED:" + peerSocket.getInetAddress().getHostName() + ":" + peerSocket.getPort());
                    output = new PrintWriter(peerSocket.getOutputStream(), true);
                    output.println("MATCHED:" + socket.getInetAddress().getHostName() + ":" + socket.getPort());
                    // 匹配完成后启用新线程处理两个客户端交流
                    new Thread(new PeerHandler(this, socket, peerSocket)).start();
                    new Thread(new PeerHandler(this, peerSocket, socket)).start();
                }
            } while (peerMatch);
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    // 用户退出后释放房间
    public void releaseRoom() {
        clients[room] = null;
        roomMatch[room] = false;
    }
}

// 接收信息说明：
// 扫雷程序进入联机模式后立刻新建客户端套接字连接服务器
// 终止信号9999999，收到此信息可以断开与客户端连接（此部分由PeerHandler处理）
// 正常对局点击信号（bb(00-20)-点击block行号，cc(00-40)-点击block列号，d(0/1)-下一行动方）bbccd
// 创建房间申请aa99999，需要回复信息aa9999d（告知行动方信息），使用一个bool数组记录房间号是否被占用，房间未建立回复行动方0，反之回复1
// 再使用一个bool数组记录房间满员状态，回复1后设置对应房间号下标元素为true，再次接收到该房间号申请信息则拒绝，回复0000000
